"""
认证视图控制器
处理基于模板的认证相关路由
"""
from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.urls import url_parse
from app.models import User
from app.forms.user_forms import UserLoginForm, UserRegistrationForm
from app import db
from app.services.oauth_service import OAuthService
from app.utils.decorators import anonymous_required, confirmed_required
from app.utils.logging_middleware import log_user_action

auth_bp = Blueprint('auth', __name__, template_folder='../../templates/auth')

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录"""
    # 如果用户已经登录，重定向到主页
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    
    form = UserLoginForm()
    if form.validate_on_submit():
        # 支持用户名或邮箱登录
        user = User.query.filter(
            (User.username == form.username.data) | (User.email == form.username.data)
        ).first()
        
        # 验证用户
        if user and user.check_password(form.password.data):
            if user.is_active:
                login_user(user, remember=form.remember_me.data)
                flash('登录成功！', 'success')
                
                # 记录登录日志
                log_user_action(
                    action='用户登录',
                    details=f'用户名: {user.username}\n记住登录: {form.remember_me.data}'
                )
                
                # 获取重定向页面
                next_page = request.args.get('next')
                if not next_page or not next_page.startswith('/'):
                    next_page = url_for('main.index')
                return redirect(next_page)
            else:
                flash('您的账户已被禁用，请联系管理员。', 'danger')
                # 记录登录失败日志
                log_user_action(
                    action='登录失败 - 账户已禁用',
                    details=f'用户名: {form.username.data}'
                )
        else:
            flash('用户名或密码错误。', 'danger')
            # 记录登录失败日志
            log_user_action(
                action='登录失败 - 密码错误',
                details=f'用户名: {form.username.data}'
            )
    
    return render_template('auth/login.html', form=form)

@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    """用户注册"""
    # 如果用户已经登录，重定向到主页
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    
    form = UserRegistrationForm()
    if form.validate_on_submit():
        # 检查用户名是否已存在
        if User.query.filter_by(username=form.username.data).first():
            flash('用户名已存在。', 'danger')
            return render_template('auth/register.html', form=form)
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=form.email.data).first():
            flash('邮箱已被注册。', 'danger')
            return render_template('auth/register.html', form=form)
        
        # 创建新用户
        user = User(
            username=form.username.data,
            email=form.email.data,
            nickname=form.nickname.data
        )
        user.set_password(form.password.data)
        
        # 默认角色（这里简化处理，实际项目中可以根据需要分配默认角色）
        from app.models import Role
        default_role = Role.query.filter_by(name='viewer').first()
        if default_role:
            user.roles.append(default_role)
        
        db.session.add(user)
        db.session.commit()
        
        # 记录用户注册日志
        log_user_action(
            action='用户注册',
            details=f'用户名: {user.username}\n邮箱: {user.email}\n昵称: {user.nickname}'
        )
        
        flash('注册成功！请登录。', 'success')
        return redirect(url_for('auth.login'))
    
    return render_template('auth/register.html', form=form)

@auth_bp.route('/logout')
@login_required
def logout():
    """用户登出"""
    # 记录登出日志
    log_user_action(
        action='用户登出',
        details=f'用户名: {current_user.username}'
    )
    
    logout_user()
    flash('您已成功登出。', 'info')
    return redirect(url_for('auth.login'))

@auth_bp.route('/profile')
@login_required
def profile():
    """用户个人资料"""
    return render_template('auth/profile.html', user=current_user)

@auth_bp.route('/change_password', methods=['GET', 'POST'])
@login_required
def change_password():
    """修改密码"""
    if request.method == 'POST':
        old_password = request.form.get('old_password')
        new_password = request.form.get('new_password')
        confirm_password = request.form.get('confirm_password')
        
        # 验证旧密码
        if not current_user.check_password(old_password):
            flash('当前密码不正确', 'danger')
            return render_template('auth/change_password.html')
        
        # 验证新密码
        if new_password != confirm_password:
            flash('两次输入的新密码不一致', 'danger')
            return render_template('auth/change_password.html')
        
        # 更新密码
        current_user.set_password(new_password)
        db.session.commit()
        
        # 记录修改密码日志
        log_user_action(
            action='修改密码',
            details=f'用户名: {current_user.username}'
        )
        
        flash('密码修改成功！', 'success')
        return redirect(url_for('auth.profile'))
    
    return render_template('auth/change_password.html')